<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <title th:text="${isNew} ? '创建新文章' : '编辑文章'">创建/编辑文章</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 20px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .container {
            max-width: 1400px;
            margin-bottom: 50px;
        }
        .page-header {
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .card {
            background-color: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 0 15px rgba(0,0,0,0.05);
        }
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            font-weight: 600;
        }
        .preview-image-container {
            position: relative;
            margin-top: 15px;
        }
        .preview-image {
            width: 100%;
            height: auto;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }
        #deleteImageBtn {
            position: absolute;
            top: 10px;
            right: 10px;
        }
        .editor-toolbar, .CodeMirror, .editor-preview-side {
            border: 1px solid #dee2e6 !important;
        }
        .editor-toolbar {
            border-bottom: none !important;
        }
        .editor-label-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 1.5rem;
            margin-bottom: 0.5rem;
        }
        
        /* 全屏模式下发布管理面板优化 */
        .editor-fullscreen .col-lg-3 {
            position: fixed !important;
            top: 20px !important;
            right: 20px !important;
            width: 300px !important;
            z-index: 99999 !important; /* 提高z-index确保在EasyMDE全屏模式之上 */
            max-height: calc(100vh - 40px) !important;
            overflow-y: auto !important;
            background-color: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(10px) !important;
            border-radius: 10px !important;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3) !important;
            padding: 15px !important;
        }
        
        .editor-fullscreen .col-lg-9 {
            width: calc(100% - 340px) !important;
        }
        
        /* 确保全屏模式下编辑器不被遮挡 */
        .editor-fullscreen .CodeMirror-fullscreen {
            z-index: 50000 !important;
        }
        
        /* 全屏模式下的工具栏样式 */
        .editor-fullscreen .editor-toolbar.fullscreen {
            z-index: 50001 !important;
        }
        
        /* 图片上传按钮样式 */
        .image-upload-btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 5px;
        }
        
        .image-upload-btn:hover {
            background: #0056b3;
        }
        
        /* 上传进度提示 */
        .upload-progress {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0, 123, 255, 0.9);
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            z-index: 10000;
            display: none;
        }
        
        .upload-error {
            background: rgba(220, 53, 69, 0.9) !important;
        }
        
        .upload-success {
            background: rgba(40, 167, 69, 0.9) !important;
        }
    </style>
</head>
<body>

<!-- 上传进度提示 -->
<div id="uploadProgress" class="upload-progress">
    <i class="bi bi-cloud-upload"></i> <span id="uploadText">正在上传图片...</span>
</div>

<div class="container">
    <div class="page-header">
        <h1><i class="bi bi-pencil-square text-primary"></i> <span th:text="${isNew} ? '创建新文章' : '编辑文章'"></span></h1>
        <div>
            <a href="/" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> 返回</a>
            <button type="submit" form="postForm" class="btn btn-primary"><i class="bi bi-save"></i> <span th:text="${isNew} ? '发布文章' : '更新文章'"></span></button>
        </div>
    </div>

    <div class="alert alert-danger" th:if="${error}" th:text="${error}"></div>

    <form th:action="${isNew} ? @{/posts/new} : @{/posts/{id}/edit(id=${post.id})}"
          method="post"
          enctype="multipart/form-data"
          th:object="${post}"
          id="postForm">

        <div class="row">
            <div class="col-lg-9">
                <div class="card">
                    <div class="card-body p-4">
                        <div class="form-group mb-3">
                            <label for="title" class="form-label fs-5">文章标题</label>
                            <input type="text" class="form-control form-control-lg" id="title" name="title" th:field="*{title}" placeholder="请输入文章标题" required>
                        </div>

                        <div class="editor-label-container">
                            <label class="form-label fs-5 mb-0">文章内容 (Markdown)</label>
                            <div>
                                <button type="button" id="preview-toggle-btn" class="btn btn-outline-secondary btn-sm">
                                    <i class="bi bi-eye"></i> 切换预览
                                </button>
                                <button type="button" id="upload-image-btn" class="image-upload-btn">
                                    <i class="bi bi-image"></i> 上传图片
                                </button>
                                <input type="file" id="image-file-input" accept="image/*" style="display: none;">
                            </div>
                        </div>

                        <div>
                            <textarea id="markdown-editor"></textarea>
                            <input type="hidden" id="markdownContent" name="markdownContent" th:value="${markdownContent ?: post.content}">
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-3">
                <div class="card sticky-top" style="top: 20px;">
                    <div class="card-header"><i class="bi bi-gear-fill"></i> 发布设置</div>
                    <div class="card-body">
                        <div class="form-group mb-3">
                            <label for="category" class="form-label">文章分类</label>
                            <select class="form-select" id="category" name="categoryId">
                                <option value="">-- 选择分类 --</option>
                                <option th:each="category : ${categories}"
                                        th:value="${category.id}"
                                        th:text="${category.name}"
                                        th:selected="${post.category != null && post.category.id == category.id}"></option>
                            </select>
                        </div>
                        <hr>
                        <div class="form-group">
                            <label for="imageFile" class="form-label">封面图片</label>
                            <input type="file" class="form-control" id="imageFile" name="imageFile" accept="image/*">
                            <div th:if="${!isNew && post.coverImageUrl != null}" id="currentImageContainer" class="preview-image-container">
                                <img th:src="${post.coverImageUrl}" class="preview-image" alt="当前封面图片" id="currentImage">
                                <button type="button" class="btn btn-danger btn-sm" id="deleteImageBtn" onclick="deleteCurrentImage()">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                            <div id="imagePreviewContainer" class="preview-image-container" style="display:none;">
                                <img id="imagePreview" class="preview-image" alt="图片预览">
                            </div>
                            <input type="hidden" name="deleteImage" id="deleteImageFlag" value="false">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
<script src="/js/turbo-fixes.js" defer></script>

<script>
    let easyMDEInstance = null;

    function initializePage() {
        console.log("页面加载完成，开始初始化编辑器...");

        const editorElement = document.getElementById('markdown-editor');
        if (!editorElement) {
            console.error("错误：找不到ID为 markdown-editor 的textarea元素。");
            return;
        }

        // 检查编辑器是否已经初始化
        if (editorElement.classList.contains('CodeMirror')) {
            console.log("编辑器已经初始化，跳过重复初始化");
            return;
        }

        let attempts = 0;
        const maxAttempts = 30;
        const interval = 100;

        const tryInit = () => {
            attempts++;
            
            if (typeof EasyMDE !== 'undefined') {
                console.log(`EasyMDE 库已加载，开始初始化编辑器... (尝试 ${attempts})`);

                // 清理旧实例
                if (easyMDEInstance) {
                    try {
                        easyMDEInstance.toTextArea();
                        easyMDEInstance = null;
                        console.log("已清理旧的编辑器实例");
                    } catch (e) {
                        console.warn("清理旧实例时出错:", e);
                        easyMDEInstance = null;
                    }
                }

                try {
                    easyMDEInstance = new EasyMDE({
                        element: editorElement,
                        spellChecker: false,
                        initialValue: document.getElementById('markdownContent').value || '',
                        maxHeight: "800px",
                        toolbar: [
                            'bold', 'italic', 'heading', '|',
                            'quote', 'code', 'unordered-list', 'ordered-list', '|',
                            'link', 'image', 'table', '|',
                            'preview', 'side-by-side', 'fullscreen', '|',
                            'guide'
                        ],
                    });

                    console.log("编辑器创建成功，高度已设置为 800px。");

                    easyMDEInstance.codemirror.on('change', () => {
                        document.getElementById('markdownContent').value = easyMDEInstance.value();
                    });
                    
                    // 标记编辑器已初始化
                    editorElement.setAttribute('data-editor-initialized', 'true');
                } catch (e) {
                    console.error("初始化编辑器时出错:", e);
                    if (attempts < maxAttempts) {
                        console.log(`${interval}ms后重试...`);
                        setTimeout(tryInit, interval);
                    }
                    return;
                }

                // 监听全屏模式切换
                easyMDEInstance.codemirror.on('optionChange', (instance, option) => {
                    if (option === 'fullScreen') {
                        const isFullscreen = instance.getOption('fullScreen');
                        const container = document.querySelector('.container');
                        if (isFullscreen) {
                            container.classList.add('editor-fullscreen');
                        } else {
                            container.classList.remove('editor-fullscreen');
                        }
                    }
                });

                // 实现剪贴板图片粘贴功能
                easyMDEInstance.codemirror.on('paste', (instance, event) => {
                    const clipboardData = event.clipboardData || window.clipboardData;
                    if (clipboardData && clipboardData.items) {
                        for (let i = 0; i < clipboardData.items.length; i++) {
                            const item = clipboardData.items[i];
                            if (item.type.indexOf('image') !== -1) {
                                event.preventDefault();
                                const file = item.getAsFile();
                                uploadImageFile(file, instance);
                                break;
                            }
                        }
                    }
                });

                // [新增] 绑定我们自定义的预览按钮
                const previewBtn = document.getElementById('preview-toggle-btn');
                if (previewBtn) {
                    previewBtn.addEventListener('click', () => {
                        if (easyMDEInstance) {
                            easyMDEInstance.togglePreview(); // 调用编辑器的预览切换API
                        }
                    });
                }

                // 绑定图片上传按钮
                const uploadBtn = document.getElementById('upload-image-btn');
                const fileInput = document.getElementById('image-file-input');
                if (uploadBtn && fileInput) {
                    uploadBtn.addEventListener('click', () => {
                        fileInput.click();
                    });
                    
                    fileInput.addEventListener('change', (event) => {
                        const file = event.target.files[0];
                        if (file) {
                            uploadImageFile(file, easyMDEInstance.codemirror);
                        }
                        // 清空文件输入框，允许重复选择同一文件
                        event.target.value = '';
                    });
                }

                const imageFileInput = document.getElementById('imageFile');
                if (imageFileInput) {
                    imageFileInput.removeEventListener('change', previewImage);
                    imageFileInput.addEventListener('change', previewImage);
                }

            } else if (attempts < maxAttempts) {
                console.log(`EasyMDE 库未加载，${interval}ms后重试... (尝试 ${attempts}/${maxAttempts})`);
                setTimeout(tryInit, interval);
            } else {
                console.error(`错误：经过 ${maxAttempts} 次尝试，EasyMDE 库仍未加载，编辑器无法初始化。`);
            }
        };

        tryInit();
    }

    // 上传图片文件到服务器
    function uploadImageFile(file, codeMirrorInstance) {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
            showUploadMessage('只能上传图片文件', 'error');
            return;
        }
        
        // 验证文件大小 (5MB)
        if (file.size > 5 * 1024 * 1024) {
            showUploadMessage('图片大小不能超过5MB', 'error');
            return;
        }
        
        const formData = new FormData();
        formData.append('image', file);
        
        // 显示上传进度
        showUploadMessage('正在上传图片...', 'progress');
        
        // 获取CSRF token
        const csrfToken = document.querySelector('meta[name="_csrf"]')?.getAttribute('content');
        const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.getAttribute('content');
        
        const headers = {
            'X-Requested-With': 'XMLHttpRequest'
        };
        
        if (csrfToken && csrfHeader) {
            headers[csrfHeader] = csrfToken;
        }
        
        fetch('/api/upload-image', {
            method: 'POST',
            body: formData,
            headers: headers
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 插入图片markdown语法到编辑器
                const imageMarkdown = `![图片](${data.url})`;
                const cursor = codeMirrorInstance.getCursor();
                codeMirrorInstance.replaceRange(imageMarkdown, cursor);
                showUploadMessage('图片上传成功', 'success');
            } else {
                showUploadMessage(data.message || '图片上传失败', 'error');
            }
        })
        .catch(error => {
            console.error('上传错误:', error);
            showUploadMessage('图片上传失败，请重试', 'error');
        });
    }
    
    // 显示上传消息
    function showUploadMessage(message, type) {
        const progressDiv = document.getElementById('uploadProgress');
        const textSpan = document.getElementById('uploadText');
        
        textSpan.textContent = message;
        progressDiv.className = 'upload-progress';
        
        if (type === 'error') {
            progressDiv.classList.add('upload-error');
        } else if (type === 'success') {
            progressDiv.classList.add('upload-success');
        }
        
        progressDiv.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            progressDiv.style.display = 'none';
        }, 3000);
    }

    function previewImage(event) {
        const file = event.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('imagePreview').src = e.target.result;
            document.getElementById('imagePreviewContainer').style.display = 'block';
            const current = document.getElementById('currentImageContainer');
            if (current) current.style.display = 'none';
        };
        reader.readAsDataURL(file);
    }

    function deleteCurrentImage() {
        if (confirm('确定要删除当前封面图片吗？')) {
            document.getElementById('currentImageContainer').style.display = 'none';
            document.getElementById('deleteImageFlag').value = 'true';
            document.getElementById('imageFile').value = '';
        }
    }

    document.addEventListener("turbo:load", initializePage);

    document.addEventListener("turbo:before-cache", function() {
        if (easyMDEInstance) {
            easyMDEInstance.toTextArea();
            easyMDEInstance = null;
            console.log("页面缓存前，已清理编辑器实例。");
        }
    });
</script>

</body>
</html>